﻿@{
    Style.Require("jQueryUI_Orchard");
    Style.Require("NineSeas.Common");
    Style.Require("NineSeas.Reader");
    Style.Require("NineSeas.Authoring");
    Style.Require("NineSeas.Authoring.Book.Edit");

    Script.Require("jQuery").AtHead();
    Script.Require("jQueryUI");
    Script.Require("NineSeas.Common");
    Script.Require("NineSeas.InplaceMessage");
    Script.Require("NineSeas.Authoring.Book.Edit");
    Script.Require("NineSeas.MediaUploadButton");
    Script.Require("NineSeas.CommandBar");
    Script.Require("FriendUrl");
    Script.Require("TinyMce");
    Script.Require("TagsAutocomplete");

    var from = Request.QueryString["from"];
}
<div id="nineseas">
    <div id="nineseas-reader-header">
        <div class="header-bullet"></div>
        @{ if (!Model.IsNew) { 
            <h1>@T("Edit book information")</h1> 
            } else {
            <h1>@T("Create new book")</h1> 
            }
        }
    </div>
    <div id="nineseas-reader-content">
        <div id="edit-area" style="width: 600px; margin: 0 auto;">
            <div class="authoring-edit-image authoring-book-image" id="imageArea">
                <img src="@Model.ImageUrl" alt="@Model.Book.Name"/>
                @T("Click to change")
            </div>        
            <div class="nineseas-field-label">@T("Name") @Display(New.Controls_HelpPopup(Message: T("The name of the book")))</div>
            <div class="nineseas-field-input">
                <input type="text" id="txtName" name="Name" value="@Model.Book.Name"/>
            </div>
            <div class="nineseas-field-label">@T("Name On Url") @Display(New.Controls_HelpPopup(Message: T("The Url address of the book (e.g. http://bellight.com/book/my-book ).<br/> Tip: this value is auto-generated as you type in the Name")))</div>
            <div class="nineseas-field-input">
                <input type="text" id="txtNameOnUrl" name="NameOnUrl" value="@Model.Book.NameOnUrl"/>
            </div>
            <div class="nineseas-field-label">@T("Tags") @Display(New.Controls_HelpPopup(Message: T("The list of keywords (a.k.a. Tags) that your book contains. These are used for search browsers to find your book.")))</div>
            <div class="nineseas-field-input">
                <input type="text" id="txtTags" name="Tags" value="@Model.Tags"/>
                <span class="hint">@T("Separate multiple tags with commas")</span>
            </div>
            <div style="clear: both;"></div>
            <div class="nineseas-field-label">@T("Categories") @Display(New.Controls_HelpPopup(Message: T("Select the category for your book.")))</div>
            <div class="nineseas-field-input">
                @Display(New.Controls_CategorySelector(
                    SelectedCategories: Model.Book.Categories,
                    Categories: Model.Categories
                ))
            </div>
            <div style="clear:both;"></div>     
            <div class="nineseas-field-label">@T("Introduction")</div>
            <div class="nineseas-field-input">
                @Html.TextArea("txtIntroduction", (string)Model.Book.Introduction, 25, 80,
	                     new Dictionary<string,object> {
		                    {"class", "html tinymce"},
                            {"style", "width:100%; height: 350px"}
	                     })
            </div>
            <div style="clear:both"></div>
        </div>         
        <input type="hidden" id="imageStoragePath" value="@Model.Book.ImageStoragePath" />
    </div>
    <div id="nineseas-reader-footer"></div>    
    <div id="throbber">
        <div class="curtain"></div>
        <div class="curtain-content">
            <div>
                <h1>@T("Processing ...")</h1>
                <p>
                    <img src="@Href("~/Modules/NineSeas/images/synchronizing.gif")" alt="" />
                </p>
            </div>
        </div>
    </div>
    @Display(New.Authoring_Book_SaveOptions())
</div>
@using (Script.Foot()) {
<script type="text/javascript">
    //<![CDATA[
    $(function () {
        var updateEditorHeight = function() {
            var newHeight = $('#nineseas-reader-content').height() - 340;
            if (newHeight < 300) newHeight = 300;

            if ($('#txtIntroduction_ifr').length > 0) {
                $('#txtIntroduction_ifr').height(newHeight);
            } else {
                    
                $('#txtIntroduction').height(newHeight + 20);
            }
        };

        $('#nineseas-reader-content').bind("heightChanged", updateEditorHeight);

        var isNew = @Model.IsNew.ToString().ToLower();
        var chaptersUrl = "@Href(String.Format("~/Authoring/Books/Book/{0}/Chapters", Model.Book.Id ?? "[BOOK_ID]"))";
        var token = "@Html.AntiForgeryTokenValueOrchard()";

        var save = function ($data, onSaveSuccess) {
            // collect the form data
            var data = $.extend({
                name: $("#txtName").val(),
                nameOnUrl: $("#txtNameOnUrl").val(),
                imageStoragePath: $('#imageStoragePath').val(),
                Tags: $("#txtTags").val(),
                //CategoryIds: 
                introduction: tinyMCE.activeEditor.getContent(),
                '__RequestVerificationToken': token
            }, $data);

            var categoryIds = [];
            $(".categorySelector .selected-items .category").each(function () {
                categoryIds.push($(this).attr("data-id"));
            });

            data.CategoryIds = categoryIds.join(",");

            $('#throbber').show();
                                
            $.post("@Url.Action("Edit", "Books", new { id = Model.Book.Id})", data, function (result) {
                $('#throbber').hide();
                if (result.success) {
                    if (isNew && result.id) {
                        chaptersUrl = chaptersUrl.replace('[BOOK_ID]', "" + result.id);
                                
                        var el = $('#nineseas-reader-footer')
                            .find("#chaptersButton")
                            .addClass('nineseas-button')
                            .removeClass('nineseas-button-disabled')
                            .bind('click', chaptersButton.onClick);
                    }

                    if (onSaveSuccess) onSaveSuccess();
                } else if (result.message) {
                    alert(result.message);
                } else {                            
                    alert('@T("An error has occurred while trying to save the data!")');
                }
            }).always(function () {$('#throbber').hide();});
        };
        var listOfBookButton = {
            id: 'listOfBookButton',
            caption: '&lt; @T("your other books")',
                onClick: function () {
                    window.location.href = '@Href("~/Authoring")';
                }
            };
        var chaptersButton = {    
            id: 'chaptersButton',
            caption: '@T("Table of Content") &gt;',
                isEnabled: !isNew,
                onClick: function () {
                    window.location.href = chaptersUrl;
                }
            };
        var saveButton = {
            id: 'saveButton',
            caption: '@T("Save")',
            onClick: function () {
                $.showSaveOptions(function (saveOptions){
                    save(saveOptions.data, function () {
                        alert('@T("The book was saved successfully.")');

                        if (saveOptions.next == 'stay') return;
                        else if (saveOptions.next == 'toc') {
                            window.location.href = chaptersUrl;
                        } else if (saveOptions.next == 'firstChapter') {
                            window.location.href = "@Model.FirstChapterLink";
                        }
                    });
                });
            }
        };
                            
        $.commandBar('#nineseas-reader-footer', {
            left: [
                listOfBookButton
            ],
            right: [saveButton, chaptersButton]
        });
            
        $('#imageArea').mediaUploadButton({
            'action': '@Url.Action("BookImage", "Upload")',
                'mediaName': 'BookImage',
                data: {
                    '__RequestVerificationToken': token
                },
                callback: function (result) {
                    if (result.success && result.filePath) {
                        $('#imageArea img').attr('src', result.publicUrl);
                        $('#imageStoragePath').val(result.filePath);
                    } else if (result.message) {
                        $.inplaceMessage({
                            type: "error",
                            messageTitle: "@T("Error:")",
                            messageContent: result.message
                        });
                    }
                }
        });

        $.tagsAutocomplete.autocomplete(
            'txtTags',
            '@Url.Action("FetchSimilarTags", new { Controller = "Admin", Area = "Orchard.Tags" })', 1);
    });
    //]]>
</script>
}